package com.cdz.bus.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdz.bus.domain.BusDockingInfo;
import com.cdz.bus.domain.BusToken;
import com.cdz.bus.service.IBusDockingInfoService;
import com.cdz.bus.service.IBusTokenService;
import com.cdz.bus.service.IRequestService;
import com.cdz.common.exception.ServiceException;
import com.cdz.common.utils.AesUtils;
import com.cdz.common.utils.DateUtils;
import com.cdz.common.utils.uuid.Seq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @program: cdz
 * @description: 充电桩-平台交互统一接口实现类
 * @author: guyi
 * @create: 2024-11-17 21:38
 **/
@Service
public class RequestServiceImpl implements IRequestService {

    private static final Logger log = LoggerFactory.getLogger(RequestServiceImpl.class);
    @Autowired
    private IBusDockingInfoService busDockingInfoService;
    @Autowired
    private IBusTokenService busTokenService;



    @Override
    public String getToken(BusDockingInfo info) throws Exception {

        QueryWrapper<BusToken> qw = new QueryWrapper<>();
        qw.eq("enterprise_code",info.getUserEnterpriseCode());
        qw.gt("expire_time",new Date());
        qw.orderByDesc("expire_time");
        qw.last("limit 1");
        BusToken one = busTokenService.getOne(qw);
        if (one != null) {
            return one.getToken();
        }
        return refreshToken(info);
    }

    @Override
    public String refreshToken(BusDockingInfo info) throws Exception {
        String data = JSONObject.of("OperatorID", info.getUserEnterpriseCode(), "OperatorSecret", info.getUserOperatorSecret()).toString();
        String encryptData = AesUtils.encrypt(data,info.getUserDataSecret(),info.getUserDataSecretIv());
        JSONObject dtoJson = new JSONObject();
        dtoJson.put("OperatorID",info.getUserEnterpriseCode());
        dtoJson.put("Data",encryptData);
        dtoJson.put("TimeStamp", DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS));
        dtoJson.put("Seq", Seq.getSeqLength(4));
        String sign = AesUtils.sign(info.getUserSigSecret(), info.getUserEnterpriseCode(),encryptData,dtoJson.getString("TimeStamp"),dtoJson.getString("Seq"));
        dtoJson.put("Sig",sign);
        String reqParams = JSONObject.toJSONString(dtoJson);
        String post = HttpUtil.post(info.getOperReqUrl() + "/query_token", reqParams);
        JSONObject jsonObject = JSONObject.parseObject(post);
        if ("0".equals(jsonObject.getString("Ret"))) {
            String voData = jsonObject.getString("Data");
            // 解密数据
            String decrypt = AesUtils.decrypt(voData, info.getUserDataSecret(), info.getUserDataSecretIv());
            JSONObject voDataJson = JSONObject.parseObject(decrypt);
            Long tokenAvailableTime = (voDataJson.getLong("TokenAvailableTime") * 1000) - 3600000; // 过期时间减一个小时
            BusToken busToken = new BusToken();
            busToken.setEnterpriseCode(voDataJson.getString("OperatorID"));
            busToken.setToken(voDataJson.getString("AccessToken"));
            busToken.setExpireTime(new Date(tokenAvailableTime));
            busToken.setCreateTime(new Date());
            busTokenService.insertBusToken(busToken);
            return jsonObject.getString("Data");
        }else{
            throw  new ServiceException(jsonObject.getString("Msg"));
        }
    }



    @Override
    public String commonRequest(String interfaceName,BusDockingInfo info,String data) throws Exception {
        String encryptData = AesUtils.encrypt(data,info.getUserDataSecret(),info.getUserDataSecretIv());
        JSONObject dtoJson = new JSONObject();
        dtoJson.put("OperatorID",info.getUserEnterpriseCode());
        dtoJson.put("Data",encryptData);
        dtoJson.put("TimeStamp", DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS));
        dtoJson.put("Seq", Seq.getSeqLength(4));
        String sign = AesUtils.sign(info.getUserSigSecret(), info.getUserEnterpriseCode(),encryptData,dtoJson.getString("TimeStamp"),dtoJson.getString("Seq"));
        dtoJson.put("Sig",sign);
        String reqParams = JSONObject.toJSONString(dtoJson);

        String reqUrl = info.getOperReqUrl() + interfaceName;
        log.info("同步数据，请求接口: {}",reqUrl);
        log.info("同步数据，请求参数: {}",reqParams);
        String postVo = HttpUtil.createPost(reqUrl)
                              .contentType("application/json")
                              .header("Authorization","Bearer "+ getToken(info)) // 设置请求头
                              .body(reqParams)
                              .execute().body();
        JSONObject voJson = JSONObject.parseObject(postVo);
        String ret = voJson.getString("Ret");
        if ("0".equals(ret)) {
            String voData = voJson.getString("Data");
            String decrypt = AesUtils.decrypt(voData, info.getUserDataSecret(), info.getUserDataSecretIv()); // 解密数据
            log.info("同步数据，响应参数: {}",decrypt);
            return decrypt;
        }else{
            String msg = voJson.getString("Msg");
            throw new ServiceException(msg);
        }
    }

}
